package com.lcj.nebula.service.impl;

import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lcj.common.exception.AochException;
import com.lcj.nebula.controller.form.SearchMonitoringForm;
import com.lcj.nebula.controller.vo.OrderMonitoringEntityVo;
import com.lcj.nebula.db.dao.OrderMonitoringDao;
import com.lcj.nebula.db.dao.OrderVoiceTextDao;
import com.lcj.nebula.db.pojo.OrderVoiceTextEntity;
import com.lcj.nebula.service.MonitoringService;
import com.lcj.nebula.task.VoiceTextCheckTask;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class MonitoringServiceImpl implements MonitoringService {
    @Resource
    private OrderVoiceTextDao orderVoiceTextDao;

    @Resource
    private OrderMonitoringDao orderMonitoringDao;

    @Resource
    private VoiceTextCheckTask voiceTextCheckTask;

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.access-key}")
    private String accessKey;

    @Value("${minio.secret-key}")
    private String secretKey;

    @Override
    @Transactional
    public void monitoring(MultipartFile file, String name, String text) {
        //把录音文件上传到Minio
        try {
            MinioClient client = new MinioClient.Builder().endpoint(endpoint).credentials(accessKey, secretKey).build();
            boolean found = client.bucketExists(BucketExistsArgs.builder().bucket("aoch-record").build());
            if(!found) {
                client.makeBucket(MakeBucketArgs.builder().bucket("aoch-record").build());
            }
            client.putObject(
                    PutObjectArgs.builder().bucket("aoch-record").object(name)
                            .stream(file.getInputStream(), -1, 20971520)
                            .contentType("audio/x-mpeg")
                            .build());
            log.info("【Minio】" + name + "上传MinIO成功");
        } catch (Exception e) {
            log.error("上传代驾录音文件失败", e);
            throw new AochException("上传代驾录音文件失败");
        }
        
        OrderVoiceTextEntity entity = new OrderVoiceTextEntity();
        
        //文件名格式例如:2156356656617-1.mp3，我们要解析出订单号
        String[] temp = name.substring(0, name.indexOf(".mp3")).split("-");
        Long orderId = Long.parseLong(temp[0]);

        String uuid = IdUtil.simpleUUID();
        entity.setUuid(uuid);
        entity.setOrderId(orderId);
        entity.setRecordFile(name);
        entity.setText(text);
        //把文稿保存到HBase
        int rows = orderVoiceTextDao.insert(entity);
        if (rows != 1) {
            throw new AochException("保存录音文稿失败");
        }
        if(text != null) {
            log.info("【同声传译】" + text);
        }

        //执行异步文稿内容审查
        voiceTextCheckTask.checkText(orderId, text, uuid);
    }

    @Override
    @Transactional
    public int insertOrderMonitoring(long orderId) {
        int rows = orderMonitoringDao.insert(orderId);
        if (rows != 1) {
            throw new AochException("添加订单监控摘要记录失败");
        }
        return rows;
    }

    @Override
    public PageInfo<OrderMonitoringEntityVo> searchOrderMonitoringByPage(SearchMonitoringForm form) {
        PageHelper.startPage(form.getPage(), form.getLength());
        List<OrderMonitoringEntityVo> orderMonitoring = orderMonitoringDao.getOrderMonitoring(form);

        PageInfo<OrderMonitoringEntityVo> pageInfo = new PageInfo<>(orderMonitoring);
        return pageInfo;
    }

    @Override
    public List<OrderVoiceTextEntity> searchOrderMonitoringDetail(Long orderId) {
        List<OrderVoiceTextEntity> list = orderVoiceTextDao.searchByOrderId(orderId);
        for(int i=0;i<list.size();i++) {
            String recordFile = list.get(i).getRecordFile();
            list.get(i).setRecordFile(endpoint + "/aoch-record/" + recordFile);
        }
        return list;
    }
}